/**
 * 异步初始化页面数据信息
 * --异步请求使用addFunction添加到实例中
 * --异步请求结束回调一定要使用functionSuccess
 * --配置异步请求完全成功后的回调
 * --实例初始化成功后需要调用start启动）
 */
layui.define('lutil', function (exports) {
    "use strict";
    var lutil = layui.lutil, layer = layui.layer, objectSet = [];

    function getObject(id) {
        var obj;
        $.each(objectSet, function (i, e) {
            if (e['index'] === id) return obj = e, false;
        });
        return obj;
    }

    var initPage = {
        index: layui.initPage ? (layui.initPage.index + 10000) : 0
    }, thisIns = function () {
        var that = this
            , options = that.config
            , id = options.id || options.index;
        return {
            addFunction: function (func) {
                if (!options.initFunctions || !(options.initFunctions instanceof Array))
                    options.initFunctions = [];
                options.initFunctions.push(func);
                return getObject(id);
            },
            functionSuccess: function () {
                if (!options.successNum) options.successNum = 0;
                if (++options.successNum === options.initFunctions.length)
                    layer.close(options.pageLoadingInc), options.pageLoadingInc = undefined
                        , options.successCallback(options.successNum);
            },
            start: function () {
                var cthat = this;
                if (!options.initFunctions || options.initFunctions.length === 0) options.successCallback();
                $.each(options.initFunctions, function (i, e) {
                    if (e !== undefined && e !== null && typeof e === 'function') e(cthat.functionSuccess);
                })
            }
            , config: options
        }
    }, Class = function (options) {
        var that = this;
        that.index = ++initPage.index;
        that.config = $.extend({}, that.config, initPage.config, options);
        that.render();
    };

    Class.prototype.config = {
        pageLoading: undefined,
        successCallback: function () {
            lutil.error_alert('请配置成功回调');
        }
    };

    Class.prototype.render = function () {
        var that = this
            , options = that.config, options
        options.pageLoadingInc = options.pageLoading || layer.load(2, {shade: [0.3, '#eee']});
    };

    initPage.render = function (options) {
        var ins = new Class(options);
        var that = thisIns.call(ins);
        objectSet.push(that);
        return that;
    };

    exports('initPage', initPage);
});